﻿using mozhi.smarterp.Finance.Finances;
using mozhi.smarterp.Finance.Querys;
using Mozhi.Abp.Core.Offices.Words;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;

namespace mozhi.smarterp.Finance.Ieps.Print
{
    public class JournalPrintHandler : PrintHandlerBase<JournalDto>
    {
        private IJournalAppService _journalAppService;

        public JournalPrintHandler(IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _journalAppService = _serviceProvider.GetService(typeof(IJournalAppService)) as IJournalAppService;
        }


        protected override async Task<List<JournalDto>> GetDataAsync(PrintQueryDto query)
        {
            var journalPageQuery = query.Filter.IsNullOrEmpty() ? new JournalPageQuery() : JsonConvert.DeserializeObject<JournalPageQuery>(query.Filter);

            journalPageQuery.IncludeDetail = true;

            var journals = await _journalAppService.FindAsync(journalPageQuery);

            return journals.Items as List<JournalDto>;
        }


        protected override List<PrintData> GetPrintDatas()
        {
            var printDatas = new List<PrintData>();

            foreach (var journal in _datas)
            {
                var printData = new PrintData();

                printData.MergeFieldDict = new Dictionary<string, string>();

                printData.MergeFieldDict.Add(nameof(JournalDto.NumberPrefix), journal.NumberPrefix);
                printData.MergeFieldDict.Add(nameof(JournalDto.Number) , journal.Number);
                printData.MergeFieldDict.Add(nameof(JournalDto.Date), journal.Date.ToString("yyyy-MM-dd"));

                printData.MergeFieldDataSet = GetJournalItemDataSet(journal);

                printDatas.Add(printData);
           
            }
            return printDatas;
        }

        #region
        private DataSet GetJournalItemDataSet(JournalDto journal)
        {
            var table = new DataTable();
            table.TableName = "Items";

            table.Columns.Add("Summary");
            table.Columns.Add("AccountName");
            table.Columns.Add("DebitAmount");
            table.Columns.Add("CreditAmount");

            foreach(var item in journal.Items)
            {
                var row = table.NewRow();

                row.ItemArray = [item.Summary, item.AccountFullName, item.DebitAmount, item.CreditAmount];

                table.Rows.Add(row);
            }

            var dataSet = new DataSet();

            dataSet.Tables.Add(table);

            return dataSet;
        }
        #endregion
    }
}
